package com.treeman.controller;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.treeman.user.User;
import com.treeman.user.service.UserService;

@Controller
public class LoginLogoutController {

	@Autowired
	private UserService userService;

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelAndView login() {

		return new ModelAndView("core/login");
	}

	@RequestMapping(value = "/ajaxlogin", method = RequestMethod.GET)
	public @ResponseBody
	LoginResult ajaxLogin(@RequestParam(value = "success") Boolean success,
			HttpServletResponse response) {

		LoginResult result = new LoginResult(success, "");

		if (result.getLoginSuccess() == false) {
			response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
		} else {
			User user = (User) SecurityContextHolder.getContext()
					.getAuthentication().getPrincipal();
			userService.login(user);
		}

		return result;
	}

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout() {
		return "redirect:/";
	}
}

class LoginResult {
	private Boolean loginSuccess;
	private String message;

	public LoginResult(Boolean loginSuccess, String message) {
		this.setLoginSuccess(loginSuccess);
		this.setMessage(message);
	}

	public Boolean getLoginSuccess() {
		return loginSuccess;
	}

	public void setLoginSuccess(Boolean loginSuccess) {
		this.loginSuccess = loginSuccess;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}
}
